package com.jj.net.tcp;

import com.jj.net.Channel;
import com.jj.net.Message;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyrights: QidianGroup@JJ
 *
 * @author: LuHan
 * @date: 2018/1/15, 13:10
 */
public class TcpChannel implements Channel{
    private static Logger logger = LoggerFactory.getLogger(TcpChannel.class);

    private ChannelHandlerContext context;

    public ChannelHandlerContext getContext() {
        return context;
    }

    public void setContext(ChannelHandlerContext context) {
        this.context = context;
    }

    @Override
    public Object remote() {
        if(context != null && context.channel()!= null)
        {
            return context.channel().remoteAddress();
        }else{
            return null;
        }
    }

    @Override
    public void send(Message msg) {
        context.channel().write(msg);
        context.channel().flush();
        logger.debug("send {} completed!", msg);
    }

    @Override
    public void close() {
        if(context == null){
            logger.warn("null context, ignore!");
            return;
        }

        if(context.channel().isActive()){
            context.channel().close();
        }else{
            logger.warn("already closed, ignore: {}", context.channel().remoteAddress());
        }
    }
}
